import logging
import threading
import time
from datetime import datetime

from playhouse import pool

from emi import report
from emi.core.DBSource import DBSource

dbsouce = DBSource.of_mysql('chinastock', host='121.196.43.113', port=3306, user='reader_chinastock',
                                                  password='5JOA2wuNuLo08pM6')

class TheThread:

    def __init__(self,index):
        self.index = index
        self.finished = False

    def start_load(self):
        t = threading.Thread(target=self.get_m1_bar)
        t.start()

    def get_m1_bar(self):
        index = self.index
        self.start_time = datetime.now()

        for i in range(0,200):
            t1 = report.start_time_event("open")

            try:
                with dbsouce._database_() as db:
                    assert db is not None
                    time.sleep(0.02)
                    if i % 20 ==0 :
                        raise RuntimeError("")
            except RuntimeError:
                pass

            db = dbsouce.create_database()
            #t1.report()
            # if i==0:
            #     print(f"db{self.index}: {db}")
            t2 = report.start_time_event("close")
            time.sleep(0.02)
            dbsouce.release_database(db)
            #t2.report()

        self.end_time = datetime.now()
        self.total_second = (self.end_time - self.start_time).total_seconds()
        self.finished = True

for i in range(0,51):
    db = dbsouce.create_database()
    print(f"db{i}: {db}")



KZT = logging.StreamHandler()

# 设置控制台日志等级
KZT.setLevel(logging.DEBUG)

# 设置控制台输出的日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
KZT.setFormatter(formatter)
logging.basicConfig(filename="test.log", format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S ',
                    level=logging.DEBUG)


# 加载控制台实例到logger对象中
pool.logger.addHandler(KZT)

pool.logger.debug("sdsf")

SIZE = 500
t_list = []
for i in range(0,SIZE):
    t = TheThread(i)
    t.start_load()
    time.sleep(0.01)
    t_list.append(t)


total_size = len(t_list)
print(f"done!")
while True:
    finished_count  = 0
    for t in t_list:
        if t.finished:
            finished_count+=1
    print(f"progress: {finished_count}/{total_size}")
    if finished_count >=total_size:
        break
    time.sleep(30)

total_time_second = 0
for t in t_list:
    total_time_second+=t.total_second

print(f"请求总个数:{total_size},平均耗时:{total_time_second/total_size:.3f}s")
